package cn.itsource.org.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /*
    *       localhost:8080/queryById?id=5
    * GET   localhost:8080/department/5
    *
    *
    *
    * PathVariable从URL路径中取值
    * */

    /*@RequestMapping("/queryById?id=")
    *
    *
    * */
    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    public Department queryById(@ApiParam(name="ID属性",required = true)@PathVariable Long id){

        return departmentService.queryById(id);
    }

    /*查询所有
    * localhost:8080/department
    * */
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.queryAll();
    }

    /*
    * 分页查询
    * 参数没打注解,默认为@RequestParam   取值:currentPage=1&pageSize=5//可在请求体中,也可在URL路径中-->key-value对格式的参数(两种)
    * @RequestBody:获取请求体中的json格式参数
    * */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }

    /*删除
    * 请求方式:delete请求
    *
    * ctrl+alt+t-----try catch
    * */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*新增/修改*/
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.add(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*批量删除*/
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*查询部门树*/
    @GetMapping("/getTree")
    public List<Department> getTree(){
        return departmentService.getTree();
    }
}
